package Day2025_03_11;

import java.util.*;

public class LeetCodeLCR114 {
    Map<Character, Set<Character>> map = new HashMap<>();
    Map<Character, Integer> in = new HashMap<>();
    boolean check;

    public String alienOrder(String[] words) {
        for (String s : words) {
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                in.put(ch, 0);
            }
        }
        int n = words.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                add(words[i], words[j]);
                if (check == true) return "";
            }
        }
        Queue<Character> q = new LinkedList<>();
        StringBuffer ret = new StringBuffer();
        for (char x : in.keySet()) if (in.get(x) == 0) q.add(x);
        while (!q.isEmpty()) {
            char t = q.poll();
            ret.append(t);
            if (!map.containsKey(t)) continue;
            for (char ch : map.get(t)) {
                in.put(ch, in.get(ch) - 1);
                if (in.get(ch) == 0) q.add(ch);
            }
        }
        for (char ch : in.keySet()) {
            if (in.get(ch) != 0) return "";
        }
        return ret.toString();
    }

    private void add (String s1, String s2) {
        int n1 = s1.length(), n2 = s2.length();
        int n = Math.min(n1, n2);
        int i = 0;
        for ( ; i < n; i++) {
            char ch1 = s1.charAt(i), ch2 = s2.charAt(i);
            if (ch1 != ch2) {
                if (!map.containsKey(ch1)) {
                    map.put(ch1, new HashSet<>());
                }
                if (!map.get(ch1).contains(ch2)) {
                    map.get(ch1).add(ch2);
                    in.put(ch2, in.get(ch2) + 1);
                }
                break;
            }
        }
        if (i == s2.length() && i < s1.length()) check = true;
    }

    public static void main(String[] args) {
        LeetCodeLCR114 leetCodeLCR114 = new LeetCodeLCR114();
        System.out.println(leetCodeLCR114.alienOrder(new String[]{"wrt","wrf","er","ett","rftt"}));
    }
}
